/**
 * @desc
 *
 * @使用场景
 *
 * @author  杨晓东[of1081]
 * @company qianmi.com
 * @Date    2017/2/12
 **/
'use strict';

var path = require('path');
var request = require('request');
var fse = require('fs-extra');
var config = require('./config/config');


let allRecordPath = path.join(__dirname, "data/all-records.json");
let allUserDatas = require(allRecordPath);


main();

async function main() {
  let access_token = await  getToken();
  console.log(access_token);
  //获取用户列表;
  let records = await getCustomList({access_token, day: -50});
  
  //对数据进入加工处理
  
  for (let i = 0, ilen = records.length; i < ilen; i++) {
    let {accountName, level, dbcVarchar10} = records[i];
    if (allUserDatas[dbcVarchar10]) {
      allUserDatas[dbcVarchar10].level = transferLv(level);
      allUserDatas[dbcVarchar10].accountName = accountName;
    } else {
      allUserDatas[dbcVarchar10] = {
        level: transferLv(level),
        accountName,
      }
    }
  }
  
  //保存到本地数据中去.
  fse.outputJson(allRecordPath, allUserDatas);
  generateUserDimension(allUserDatas);
}

let demensionMap = {
  d2cStore: {}
}

/**
 * 自动生成用户维度上传列表文件 ;;
 */
function generateUserDimension(userReords = {}) {
  
  let result = [];
  
  for (let uid in userReords) {
    result.push(`${uid},${userReords[uid].level}类用户`);
  }
  
  config.gaConfig.webPropertys.forEach(webPropertyItem => {
    fse.outputFile(path.join(__dirname, '/output/all-' + webPropertyItem.name + '.csv'), ["ga:userId," + webPropertyItem.demensionMap.userLv].concat(result).join('\r\n'), function (err) {
    })
  });
}

/**
 * 转换级别名称
 1 A
 2 B
 3 C
 5 B+
 
 * @param lv
 */
function transferLv(lv) {
  switch (lv) {
    case 1 :
      return "A";
    case 2 :
      return "B";
    case 3 :
      return "C";
    case 4 :
      return "B+";
  }
  
  return "C";
}


/**
 * 获取员工用户列表
 * @param access_token
 * @return {Promise}
 */
function getUserList({access_token}) {
  return new Promise((resolve, reject) => {
    
    console.log('获取用户列表', access_token);
    request({
      url: 'https://api.xiaoshouyi.com/data/v1/objects/user/list?start=0&count=20&access_token=' + access_token + "&Authorization=Bearer",
      method: 'post',
      headers: {
        "Content-Type": "application/json;charset=utf-8",
      }
    }, function (error, response, body) {
      console.log(body);
      resolve(body);
    });
  });
}

/**
 * 执行http 请求:
 * @return {Promise}
 */
function execHttpRequest({form, url, headers, method = "post"}) {
  return new Promise((resolve, reject) => {
    request({
      url,
      method,
      form,
      headers
    }, function (error, response, body) {
      let result = JSON.parse(body);
      resolve(result);
    });
  });
}


/**
 * 获取客户列表
 * @param access_token
 * @param start 查询起始位置
 * @param end 查询结束位置
 */
async function getCustomList({access_token, day = 0}) {
  
  let timeStamp = getDateStamp({day});
  let allRecords = [], pageNo = 0, _totalSize = 0;
  do {
    let start = pageNo * 30, end = (pageNo + 1) * 30;
    let {totalSize, records}  = await execHttpRequest({
      url: 'https://api.xiaoshouyi.com/data/v1/query?access_token=' + access_token + "&Authorization=Bearer",
      method: 'post',
      form: {
        q: `
        select id,accountName,level,dbcVarchar10 ,updatedAt
        from Account
        where level is not null 
        and dbcVarchar10 is not null
        and updatedAt > ${timeStamp}
        order by updatedAt desc limit ${start},${end}`
      },
      headers: {
        "Content-Type": "application/json;charset=utf-8",
      }
    });
    
    console.log('请求数据 : pageNo', pageNo, "totalSize:", totalSize);
    _totalSize = totalSize;
    allRecords = allRecords.concat(records);
    pageNo++;
  } while (allRecords.length < _totalSize);
  
  return allRecords;
  
}
/**
 * 当天操作的内容;
 * @return {*}
 */
function getDateStamp({day = 0}) {
  let date = new Date();
  let dateResult = new Date(date.getFullYear(), date.getMonth(), date.getDate() + day, 0, 0, 0);
  console.log('请求处理时间::', dateResult.toString());
  return dateResult.getTime();
}


//curl -X GET -H "Authorization: Bearer 44c3f796df276e954d1f1008939038b801d42e4360ffc52776d60b082347a2bd" "https://api.xiaoshouyi.com/data/v1/objects/user/list?start=0&count=20"


/**
 *
 {
   "id": 484054,
   "access_token": "44c3f796df276e954d1f1008939038b801d42e4360ffc52776d60b082347a2bd",
   "issued_at": 1486827240860,
   "token_type": "Bearer"
 }
 * @return {Promise}
 */
function getToken() {
  const client_id = '6447ef9d6485548c311fbb6509dbcbdd',
     client_secret = 'f2e7ce1bebf98904e8efd6883a742745',
     username = 'lijinguo@qianmi.com',
     password = 'hzlijinguo88',
     key = 'iee418Xn',
     redirect_uri = 'http://gateway.boss.qianmi.com';
  
  return new Promise((resolve, reject) => {
    
    let tokenUrl = "https://api.xiaoshouyi.com/oauth2/token" + "?grant_type=password&client_id=" + client_id + "&client_secret=" + client_secret
       + "&redirect_uri=" + redirect_uri + "&username=" + username + "&password=" + password + key;
    
    request(tokenUrl, function (error, response, body) {
      let result = JSON.parse(body);
      console.log(body);
      resolve(result.access_token);
    })
  });
}